import pandas as pd
import os
import time
import glob
import py2
import plotly.graph_objs as go


class Ddang_clera:
    def __init__(self):
        self.df = None
        self.path = None
        fails = os.listdir('./')
        print(fails)
        if len(fails):
            for i in fails:
                if "图书" in i:
                    s = os.path.abspath(i)
                    self.path = s
                    print(self.path)
                    break
        else:
            print('没有找到文件')

    def get_fail(self):
        if self.path:
            df = pd.read_csv('/Users/user/PycharmProjects/text1/和鲸社区项目/图书数据集.csv', sep='\t')
            print(df.head())
            self.df = df
        else:
            print('文件路径出错')

    def handle_fail(self):
        try:
            self.df['单价'] = self.df['当前价格'].str.replace('¥', '')
            self.df['单价'] = self.df['单价'].astype(float)
            print(self.df.单价)
            self.df['pinglun'] = self.df['评论数'].str.replace('条评论', '').astype('int64')
            self.df['xingji'] = self.df['星级'].str.replace('width:', '')
            self.df['xingji'] = self.df['xingji'].str.replace('%;', '').astype('int')
            self.df['xingji'] = self.df['xingji'].apply(self.fun)
            self.df['作者'] = self.df['出版信息'].apply(lambda x: x.split('/')[0])
            print(self.df['作者'])
            self.df['出版社'] = self.df['出版信息'].apply(lambda x: x.split('/', 2)[-1])  # 有点问题
            self.df['出版时间'] = self.df['出版信息'].apply(
                lambda x: x.split('/', 2)[1] if len(x.split('/', 2)) == 3 else "佚名")  # 有点问题
            print(self.df)
            self.df['shuming_replace'] = self.df['书名'].str.replace('【', '')
            self.df['shuming_replace'] = self.df['shuming_replace'].str.replace('】', '')
            self.df['shuming_replace_replace'] = self.df['shuming_replace'].str.replace('[', '')
            self.df['shuming_replace_replace'] = self.df['shuming_replace_replace'].str.replace(']', '')
            self.df['name'] = self.df['shuming_replace_replace'].apply(lambda x: x.split()[0])
            print(self.df['name'])
            self.df['jianjie'] = self.df['shuming_replace_replace'].apply(
                lambda x: x.split()[1] if len(x.split()) != 1 else '无')
            self.df['jianjie2'] = self.df['shuming_replace_replace'].apply(
                lambda x: x.split()[2] if len(x.split()) == 3 else '无')
            df = self.df.drop(
                columns=['书名', '出版信息', '当前价格', '星级', '评论数', 'shuming_replace',
                         'shuming_replace_replace'])
            df.rename(columns={'name': '书名', 'jianjie': '简介', 'pinglun': '评论', 'xingji': '星级'}, inplace=True)
            print(df.columns)
            df = df.reindex(['书名', '单价', '作者', '出版时间', '出版社', '星级', '评论', '简介', ],
                            axis=1)
            print(df.head())
            print(df.describe())
            print(df.groupby(['出版社']).size().sort_values(ascending=False))
            star_num = df.groupby(['星级']).size()
            # self.plt_data(star_num)
            # price = df['单价'].tolist
            # cats = pd.cut(price , 20 ,labels=False)
            # price1 = df.value_counts(cats).sort_index()
            # price1  = df.groupby(cats).size().sort_index()
            self.box(df['单价'])

            more = df[df['单价'] > 100]
            print(more.head())
            c = df['单价'].groupby(df['出版社']).mean()
            print(c)
        except:
            print('出错')

        def plt_data(self, x):
            inde = x.index.tolist
            num = x.values.tolist
            print(inde)
            print(num)
            fig = go.Figure()
            fig.add_trace(go.Bar(
                x=inde,
                y=num,
            ))
            fig.update_layout(title='星级图鉴')
            fig.show()

    def box(self, x):
        fig = go.Figure()
        fig.add_trace(go.Box(
            y=x,
            name='jiage',
            jitter=0.1,
            boxpoints='all',
            pointpos=0

        ))
        fig.update_layout(
            title='价格图例'
        )
        fig.show()

    def fun(self, x):
        if x == 100:
            return '5星'
        elif x == 90:
            return '4星半'
        elif x == 80:
            return '4星'
        elif x == 70:
            return '3星半'
        elif x == 60:
            return '3星'
        elif x == 50:
            return '2星半'
        elif x == 40:
            return '2星'
        elif x == 30:
            return '1星半'
        elif x == 20:
            return '1星'
        elif x == 10:
            return '半星'
        else:
            return '0星'


if __name__ == "__main__":
    start = time.time()
    dang = Ddang_clera()
    dang.get_fail()

    dang.handle_fail()
    print(f'{round(time.time() - start, 2)}秒')
